package com.zhuiyun.project.api.system.businesDept.service.impl;

import com.zhuiyun.project.api.system.businesDept.entity.SysDept;
import com.zhuiyun.project.api.system.businesDept.mapper.SysBusinesDeptMapper;
import com.zhuiyun.project.api.system.businesDept.service.SysBusinesDeptService;
import com.zhuiyun.project.api.system.menu.entity.TreeSelect;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.common.constant.UserConstants;
import com.zhuiyun.project.common.core.text.Convert;
import com.zhuiyun.project.common.exception.ServiceException;
import com.zhuiyun.project.utils.SecurityUtils;
import com.zhuiyun.project.utils.SpringUtils;
import com.zhuiyun.project.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static net.bytebuddy.matcher.ElementMatchers.hasChild;

/**
 * @ClassName SysBusinesDeptServiceImpl
 * @Description TODO 租户部门管理 服务实现
 * @Author wx
 * @Date 2023/12/5 20:59
 **/
@Service
public class SysBusinesDeptServiceImpl implements SysBusinesDeptService {
    @Autowired
    private
    SysBusinesDeptMapper sysBusinesDeptMapper;

    /**
     * @Author wx
     * @Description 获取租户部门列表
     * @Date 2023/12/6 8:51
     * @Return
     * @param dept
     */
    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        List<SysDept> tenantDepts = sysBusinesDeptMapper.selectDeptList(dept);
        return tenantDepts;
    }

    /**
    * @Author wx
    * @Description 校验部门名称是否唯一
    * @Date 2023/12/6 9:53
    * @Return
    * @param dept
    */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = sysBusinesDeptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId(),dept.getVenueUniqueIdentifier());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
    * @Author wx
    * @Description 新增部门信息
    * @Date 2023/12/6 9:59
    * @Return
    * @param dept
    */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = sysBusinesDeptMapper.selectDeptById(dept.getParentId(),dept.getVenueUniqueIdentifier());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return sysBusinesDeptMapper.insertDept(dept);
    }

    /**
    * @Author wx
    * @Description 查询权限
    * @Date 2023/12/6 14:18
    * @Return
    * @param deptId
    */
    @Override
    public void checkDeptDataScope(Long deptId, String venueUniqueIdentifier) {
        if (!SysUser.isAdmin(SecurityUtils.getParentId()))
        {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
    * @Author wx
    * @Description
    * @Date 2023/12/6 10:45
    * @Return
    * @param deptId
    */
    @Override
    public SysDept selectDeptById(Long deptId, String venueUniqueIdentifier) {
        return sysBusinesDeptMapper.selectDeptById(deptId,venueUniqueIdentifier);
    }

    /**
     * @Author wx
     * @Description 根据id查询所有子部门
     * @Date 2023/12/6 11:41
     * @Return
     * @param deptId
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId, String venueUniqueIdentifier) {
        return sysBusinesDeptMapper.selectNormalChildrenDeptById(deptId,venueUniqueIdentifier);
    }

    /**
     * @Author wx
     * @Description 修改部门信息
     * @Date 2023/12/6 11:45
     * @Return
     * @param dept
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = sysBusinesDeptMapper.selectDeptById(dept.getParentId(), dept.getVenueUniqueIdentifier());
        SysDept oldDept = sysBusinesDeptMapper.selectDeptById(dept.getDeptId(), dept.getVenueUniqueIdentifier());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors,dept.getVenueUniqueIdentifier());
        }
        int result = sysBusinesDeptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * @Author wx
     * @Description 是否存在部门子节点
     * @Date 2023/12/6 14:10
     * @Return
     * @param deptId
     */
    @Override
    public boolean hasChildByDeptId(Long deptId, String venueUniqueIdentifier) {
        int result = sysBusinesDeptMapper.hasChildByDeptId(deptId,venueUniqueIdentifier);
        return result > 0;
    }

    /**
     * @Author wx
     * @Description 查询部门是否存在用户
     * @Date 2023/12/6 14:16
     * @Return
     * @param deptId
     */
    @Override
    public boolean checkDeptExistUser(Long deptId, String venueUniqueIdentifier) {
        int result = sysBusinesDeptMapper.checkDeptExistUser(deptId,venueUniqueIdentifier);
        return result > 0;
    }

    /**
     * @Author wx
     * @Description 删除部门信息
     * @Date 2023/12/6 14:19
     * @Return
     * @param deptId
     */
    @Override
    public int deleteDeptById(Long deptId, String venueUniqueIdentifier) {
        return sysBusinesDeptMapper.deleteDeptById(deptId,venueUniqueIdentifier);
    }

    /**
     * @Author wx
     * @Description 查询部门下拉树结构
     * @Date 2023/12/7 14:41
     * @Return
     * @param venueUniqueIdentifier
     */
    @Override
    @Transactional
    public List<TreeSelect> selectDeptTreeList(String venueUniqueIdentifier) {
        SysDept dept = new SysDept();
        dept.setVenueUniqueIdentifier(venueUniqueIdentifier);
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
    * @Author wx
    * @Description 构建前端所需要下拉树结构
    * @Date 2023/12/7 14:52
    * @Return 
    * @param depts
    */
    private List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
    * @Author wx
    * @Description 构建前端所需要树结构
    * @Date 2023/12/7 14:53
    * @Return
    * @param depts
    */
    private List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
    * @Author wx
    * @Description 递归列表
    * @Date 2023/12/7 14:54
    * @Return
    * @param list
    */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors,String venueUniqueIdentifier) {
        List<SysDept> children = sysBusinesDeptMapper.selectChildrenDeptById(deptId,venueUniqueIdentifier);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            sysBusinesDeptMapper.updateDeptChildren(children,venueUniqueIdentifier);
        }
    }
    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        sysBusinesDeptMapper.updateDeptStatusNormal(dept.getVenueUniqueIdentifier(),deptIds);
    }
}
